package cn.iocoder.yudao.module.product.controller.app.comment;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.product.api.spu.ProductSpuApi;
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentCreateReqVO;
import cn.iocoder.yudao.module.product.controller.app.comment.vo.AppCommentPageReqVO;
import cn.iocoder.yudao.module.product.controller.app.comment.vo.AppProductCommentRespVO;
import cn.iocoder.yudao.module.product.controller.app.comment.vo.CommentLikeReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.comment.ProductCommentDO;
import cn.iocoder.yudao.module.product.service.comment.CommentLikeService;
import cn.iocoder.yudao.module.product.service.comment.ProductCommentService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.merchant.MerchantService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * @author wzy
 */
@Tag(name = "用户 APP - 商品评价")
@RestController
@RequestMapping("/product/comment")
@Validated
public class AppProductCommentController {
    @Resource
    private MerchantService merchantService;
    @Resource
    private ProductCommentService productCommentService;
    @Resource
    private CommentLikeService commentLikeService;
    @Resource
    private AdminUserService userService;
    @Resource
    private ProductSpuApi productSpuApi;

    @GetMapping("/page")
    @Operation(summary = "获得商品评价分页")
    public CommonResult<PageResult<AppProductCommentRespVO>> getCommentPage(@Valid AppCommentPageReqVO pageVO) {
        // 查询评论分页
        PageResult<ProductCommentDO> pageResult = productCommentService.getCommentPage(pageVO, Boolean.TRUE);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }

        // 拼接返回
        List<AppProductCommentRespVO> responseList = new ArrayList<>();
        pageResult.getList().forEach(item -> {
            AppProductCommentRespVO responseVO = BeanUtils.toBean(item, AppProductCommentRespVO.class);

            if (Boolean.TRUE.equals(item.getAnonymous())) {
                responseVO.setUserNickname(ProductCommentDO.NICKNAME_ANONYMOUS);
            }

            // 设置点赞量和评论状态
            responseVO.setLikesCount(productCommentService.getCountLikes(item.getId())); // 假设 item 有 getLikesCount() 方法
            responseVO.setLikeStatus(productCommentService.getLikeStatus(item.getId()));   // 假设 item 有 isCommented() 方法
            Long creator = productSpuApi.getSpu(responseVO.getSpuId()).getCreator();
            String merchantName = merchantService.getMerchantNameById(creator);
            responseVO.setMerchantName(merchantName);
            responseList.add(responseVO);
        });


        return success(new PageResult<>(responseList, pageResult.getTotal()));
    }

    @GetMapping("/selfPage")
    @Operation(summary = "获得个人商品评价分页")
    @PreAuthenticated
    public CommonResult<PageResult<AppProductCommentRespVO>> getSelfCommentPage(PageParam pageVo) {
        // 查询评论分页
        Long userId = getLoginUserId();
        PageResult<ProductCommentDO> pageResult = productCommentService.getSelfCommentPage(pageVo, userId);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }

        // 拼接返回
        List<AppProductCommentRespVO> responseList = new ArrayList<>();
        pageResult.getList().forEach(item -> {
            AppProductCommentRespVO responseVO = BeanUtils.toBean(item, AppProductCommentRespVO.class);

            if (Boolean.TRUE.equals(item.getAnonymous())) {
                responseVO.setUserNickname(ProductCommentDO.NICKNAME_ANONYMOUS);
            }

            // 设置点赞量和评论状态
            responseVO.setLikesCount(productCommentService.getCountLikes(item.getId())); // 假设 item 有 getLikesCount() 方法
            responseVO.setLikeStatus(productCommentService.getLikeStatus(item.getId()));   // 假设 item 有 isCommented() 方法
            Long creator = productSpuApi.getSpu(responseVO.getSpuId()).getCreator();
            String merchantName = merchantService.getMerchantNameById(creator);
            responseVO.setMerchantName(merchantName != null ? merchantName : "未知商户");

            responseList.add(responseVO);
        });


        return success(new PageResult<>(responseList, pageResult.getTotal()));
    }


    // 点赞接口
    @PostMapping("/like")
    @Operation(summary = "评论点赞")
    @PreAuthenticated
    public ResponseEntity<String> likeComment(@Valid @RequestBody CommentLikeReqVO reqVO) {
        commentLikeService.likeComment(reqVO);
        return ResponseEntity.ok("点赞成功");
    }

    @PostMapping("/unlike")
    @Operation(summary = "取消点赞")
    @PreAuthenticated
    public ResponseEntity<String> unlikeComment(@Valid @RequestBody CommentLikeReqVO reqVO) {
        commentLikeService.unlikeComment(reqVO);
        return ResponseEntity.ok("已取消成功");
    }

    @PostMapping("/create")
    @Operation(summary = "添加评论")
    @PreAuthenticated
    public CommonResult<Boolean> createComment(@Valid @RequestBody ProductCommentCreateReqVO createReqVO) {
        LoginUser user = getLoginUser();
        if (user != null) {
            AdminUserDO admin = userService.getUser(user.getId());
            createReqVO.setUserId(admin.getId());
            createReqVO.setUserNickname(admin.getUsername());
            createReqVO.setUserAvatar(admin.getAvatar());
        }


        productCommentService.createComment(createReqVO);
        return success(true);
    }


    @PostMapping("/createAdditional")
    @Operation(summary = "追加评论")
    @PreAuthenticated
    public CommonResult<Boolean> additionalCreateComment(@Valid @RequestBody ProductCommentCreateReqVO createReqVO) {
        LoginUser user = getLoginUser();
        if (user != null) {
            AdminUserDO admin = userService.getUser(user.getId());
            createReqVO.setUserId(admin.getId());
            createReqVO.setUserNickname(admin.getUsername());
            createReqVO.setUserAvatar(admin.getAvatar());
        }
        productCommentService.createAdditionalComment(createReqVO);
        return success(true);
    }


}
